//
//  Log.swift
//  TestTools
//
//  Created by MAC on 2023/3/3.
//

import Foundation

public enum LogLevel {
    case info
    case warning
    case error
}


/// 输出日志
/// - Parameters:
///   - message: T 日志内容
///   - file: String 日志内容所在文件
///   - funcName: String 日志内容所在方法
///   - lineNum: Int 日志内容所在行号
///   - level: LogLevel 日志级别，info, warning, error
///   - onlyShowContent: Bool 仅显示内容，不显示文件名、方法名、行号，默认值 false
///   - isOutput:Bool 是否输出到文件，默认值 true
public func Print<T>(_ message:T, file : String = #file, funcName : String = #function, lineNum : Int = #line, level : LogLevel = .info, onlyShowContent : Bool = false, isOutput: Bool = true) {
    
    let fileName = (file as NSString).lastPathComponent
    
    let msg = "\(message)"
    
    var levelDes = ""
    
    switch level {
        
    case .info:
        levelDes = "💚"
    case .warning:
        levelDes = "🟨"
    case .error:
        levelDes = "🔴"
    }
    
    var content = msg.isEmpty ? "" : "\(Date().current), line: \(String(format: "%4d", lineNum)), level: \(levelDes), file: \(fileName), func: \(funcName), log: \(message)"
    //❌🔸🔻🔴🟠🟡🟢❤️🧡💛💚🟥🟧🟨🟩
    if onlyShowContent {
        content = "\(message)"
    }
#if DEBUG
    print("\(content)")
#endif
    if isOutput {
        do {
            let fileName = "\(Date().toString()).log"
            if let dir: URL = getDirectory() {
                let url = dir.appendingPathComponent(fileName)
                try content.appendLineToURL(fileURL: url as URL)
            }
            // let result = try String(contentsOf: url as URL, encoding: String.Encoding.utf8)
        } catch {
    #if DEBUG
            print("Could not write to file")
    #endif
        }
    }
}


/// 获取目录
/// - Parameter directoryName: 目录名称，默认Log
/// - Returns: 目录地址
public func getDirectory(directoryName: String = "Log") -> URL? {
    let fileManager = FileManager.default
    //    let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
    guard let documentsURL = getRootDirectory() else { return nil }
    let directoryURL = documentsURL.appendingPathComponent(directoryName)
    
    if !fileManager.fileExists(atPath: directoryURL.path) {
        do {
            try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil)
            print("\(directoryName) directory created successfully")
            return directoryURL
        } catch {
            print("Error creating \(directoryName.lowercased()) directory: \(error)")
            return nil
        }
    } else {
        return directoryURL
    }
}

public func getRootDirectory() -> URL? {
    
    guard let bundleIdentifier = Bundle.main.infoDictionary?["CFBundleIdentifier"] as? String else { return nil }
    let fileManager = FileManager.default
    var rootURL: URL?
    
#if os(OSX)
    rootURL = fileManager.containerURL(forSecurityApplicationGroupIdentifier: bundleIdentifier)
    if let path = rootURL?.path, !fileManager.fileExists(atPath: path) {
        print("目录：\(path) 不存在")
        rootURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
    }
#else
    rootURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
#endif
    
    // print("获取根目录：\(rootURL?.path ?? "")")
    return rootURL
}

public func deleteLogFilesBefore(date: Date, directoryName: String) {
    let fileManager = FileManager.default
    guard let documentsDirectory = getDirectory(directoryName: directoryName) else { return }

    do {
        let directoryContents = try fileManager.contentsOfDirectory(at: documentsDirectory, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        
        for fileURL in directoryContents {
            let creationDate = try fileManager.attributesOfItem(atPath: fileURL.path)[.creationDate] as! Date
            if creationDate < date {
                try fileManager.removeItem(at: fileURL)
                print("Deleted file: \(fileURL.lastPathComponent)")
            }
        }
    } catch {
        print("Error while enumerating files: \(error.localizedDescription)")
    }
}
